package com.topvision.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件帮助类
 *
 * @author shengwm
 * @create 2018-04-25 11:34
 **/
public class ArFileUtil {

    public static Map<String, Object> getFile(HttpServletRequest request, String param) {

        Map<String, Object> map = new HashMap<>();

        //获取输入流
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        InputStream inputStream = null;
        InputStream ftpInputStream = null;

        // 文件类型
        String type = null;
        String fileName = null;

        //转换成多媒体请求
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;


        try {
            inputStream = multiRequest.getFile(param).getInputStream();
            fileName = multiRequest.getFile(param).getOriginalFilename();
            ftpInputStream = multiRequest.getFile(param).getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }


        type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
        LocalDate today = LocalDate.now();
        String dir = today.toString().replace("-", "/");
        String filename = String.valueOf(System.currentTimeMillis());
        String name = type != null ? filename + "." + type : filename + ".jpg";

        File tmpFile = null;
        String tmpname = FilenameUtils.getExtension(fileName);
        //手动创建临时文件
        tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + dir + "/" + fileName);
        try {
            FileUtils.copyInputStreamToFile(inputStream, tmpFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("file", tmpFile);
        map.put("ftpstream", ftpInputStream);
        map.put("name", name);

        return map;
    }
}
